package com.usian.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserServcie;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.List;

@Service
public class WmUserServcieImpl extends BaseServiceImpl<WmUserMapper, WmUser> implements WmUserServcie {

    @Override
    public ResponseResult inster(WmUser wmUser) {
        if (wmUser==null)return paramInvalid;
        save(wmUser);
        return success;
    }

    @Override
    public WmUser findByName(String name) {
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName,name);
        List<WmUser> list = list(wrapper);
        if (list!=null&&!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }

    @Override
    public ResponseResult login(WmUserDto dto) {
        //校验用户密码不能为空
        if (StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户或密码错误");
        }
        //2.查找数据库的用户信息
        List<WmUser> list = list(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (list!=null&&list.size()==1){
            WmUser wmUser = list.get(0);
            //3.密码对比
            String pswd= DigestUtils.md5DigestAsHex((dto.getPassword()+wmUser.getSalt()).getBytes());
            if (wmUser.getPassword().equals(pswd)){
                //4.返回数据jwt
                HashMap<Object, Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(wmUser.getApUserId().longValue()));//生成token
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("user",wmUser);
               return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_NamePASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

    }
}
